/*
 * Copyright (C), 2015-2019
 * FileName: JStack
 * Author:   lizhao
 * Date:     2019-02-12 19:55
 * Description: 虚拟机栈结构
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.jjvm.runtime;

import java.util.EmptyStackException;

/**
 * 〈一句话功能简述〉<br>
 * 〈虚拟机栈结构〉
 *
 * @author lizhao
 * @date 2019-02-12 19:55
 * @since 1.0.0
 */
public class JStack {
    private int maxSize;// 最大栈大小
    private int size;// 当前栈大小
    private Frame top;// 第一个帧，栈顶

    public JStack(int maxSize) {
        this.maxSize = maxSize;
    }

    public void push(Frame frame) {
        if (size >= maxSize) {
            throw new StackOverflowError();
        }

        if (top != null) {
            frame.setLower(top);
        }
        top = frame;
        size++;
    }

    public Frame pop() {
        if (top == null) {
            System.out.println("JStack top is empty");
            throw new EmptyStackException();
        }
        Frame result = top;
        top = top.getLower();
        result.setLower(null);
        size--;
        return top;
    }

    public Frame top() {
        if (top == null) {
            System.out.println("JStack top is empty");
            throw new EmptyStackException();
        }
        return top;
    }

}
